using System.Collections.Generic;
using JlPay.Sdk.Models;
using System;
using System.Text.Json;
using System.Linq;

namespace JlPay.Sdk.Models.Marketing
{
    /// <summary>
    /// 营销活动数据
    /// </summary>
    public class MarketingActivityData
    {
        /// <summary>
        /// 活动ID
        /// </summary>
        public string? ActId { get; set; }

        /// <summary>
        /// 活动名称
        /// </summary>
        public string? ActName { get; set; }

        /// <summary>
        /// 赞助商ID
        /// </summary>
        public string? SponsorId { get; set; }

        /// <summary>
        /// 赞助商名称
        /// </summary>
        public string? SponsorName { get; set; }

        /// <summary>
        /// 活动开始时间
        /// </summary>
        public string? StartTime { get; set; }

        /// <summary>
        /// 活动结束时间
        /// </summary>
        public string? EndTime { get; set; }

        /// <summary>
        /// 活动状态
        /// </summary>
        public string? Status { get; set; }

        /// <summary>
        /// 活动类型
        /// </summary>
        public string? ActType { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public string? CreateTime { get; set; }

        /// <summary>
        /// 更新时间
        /// </summary>
        public string? UpdateTime { get; set; }
    }

    /// <summary>
    /// 营销活动查询响应模型
    /// </summary>
    public class MarketingActivityQueryResponse : StandardResponse
    {
        /// <summary>
        /// 营销活动数据列表
        /// </summary>
        public List<MarketingActivityData>? Data { get; set; }

        /// <summary>
        /// 总数量
        /// </summary>
        public string? Total { get; set; }

        /// <summary>
        /// 页码
        /// </summary>
        public string? Page { get; set; }

        /// <summary>
        /// 每页数量
        /// </summary>
        public string? Limit { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public MarketingActivityQueryResponse()
        {
            Data = new List<MarketingActivityData>();
        }

        /// <summary>
        /// 构造函数，用于解析API响应数据
        /// </summary>
        /// <param name="responseDict">响应字典</param>
        public MarketingActivityQueryResponse(Dictionary<string, object>? responseDict) : this()
        {
            if (responseDict != null)
            {
                // 解析基础字段
                if (responseDict.TryGetValue("ret_code", out var retCode))
                    RetCode = retCode?.ToString();
                
                if (responseDict.TryGetValue("ret_msg", out var retMsg))
                    RetMsg = retMsg?.ToString();

                // 解析分页字段
                if (responseDict.TryGetValue("total", out var total))
                    Total = total?.ToString();
                
                if (responseDict.TryGetValue("page", out var page))
                    Page = page?.ToString();
                
                if (responseDict.TryGetValue("limit", out var limit))
                    Limit = limit?.ToString();

                // 解析活动数据列表 - 改进类型检查
                if (responseDict.TryGetValue("data", out var dataValue))
                {
                    // 调试信息
                    Console.WriteLine($"Debug: dataValue type = {dataValue?.GetType().Name}");
                    Console.WriteLine($"Debug: dataValue value = {dataValue}");
                    
                    if (dataValue != null)
                    {
                        // 处理不同类型的data值
                        if (dataValue is List<object> dataList)
                        {
                            Console.WriteLine($"Debug: Processing List<object> with {dataList.Count} items");
                            ProcessDataList(dataList);
                        }
                        else if (dataValue is object[] dataArray)
                        {
                            Console.WriteLine($"Debug: Processing object[] with {dataArray.Length} items");
                            ProcessDataArray(dataArray);
                        }
                        else if (dataValue is JsonElement jsonElement)
                        {
                            Console.WriteLine($"Debug: Processing JsonElement");
                            ProcessJsonElement(jsonElement);
                        }
                        else
                        {
                            Console.WriteLine($"Debug: Unknown data type, attempting to convert");
                            // 尝试转换为List<object>
                            try
                            {
                                if (dataValue is IEnumerable<object> enumerable)
                                {
                                    var list = enumerable.ToList();
                                    Console.WriteLine($"Debug: Converted to List with {list.Count} items");
                                    ProcessDataList(list);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($"Debug: Conversion failed: {ex.Message}");
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 处理数据列表
        /// </summary>
        /// <param name="dataList">数据列表</param>
        private void ProcessDataList(List<object> dataList)
        {
            foreach (var item in dataList)
            {
                if (item is Dictionary<string, object> itemDict)
                {
                    var dataItem = CreateMarketingActivityData(itemDict);
                    Data?.Add(dataItem);
                }
            }
        }

        /// <summary>
        /// 处理数据数组
        /// </summary>
        /// <param name="dataArray">数据数组</param>
        private void ProcessDataArray(object[] dataArray)
        {
            foreach (var item in dataArray)
            {
                if (item is Dictionary<string, object> itemDict)
                {
                    var dataItem = CreateMarketingActivityData(itemDict);
                    Data?.Add(dataItem);
                }
            }
        }

        /// <summary>
        /// 处理JsonElement
        /// </summary>
        /// <param name="jsonElement">JSON元素</param>
        private void ProcessJsonElement(JsonElement jsonElement)
        {
            if (jsonElement.ValueKind == JsonValueKind.Array)
            {
                foreach (var element in jsonElement.EnumerateArray())
                {
                    if (element.ValueKind == JsonValueKind.Object)
                    {
                        var itemDict = JsonSerializer.Deserialize<Dictionary<string, object>>(element.GetRawText());
                        if (itemDict != null)
                        {
                            var dataItem = CreateMarketingActivityData(itemDict);
                            Data?.Add(dataItem);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 创建营销活动数据对象
        /// </summary>
        /// <param name="itemDict">数据字典</param>
        /// <returns>营销活动数据对象</returns>
        private MarketingActivityData CreateMarketingActivityData(Dictionary<string, object> itemDict)
        {
            var dataItem = new MarketingActivityData();
            
            // 处理API返回的字段，进行字段名映射
            if (itemDict.TryGetValue("act_id", out var actId))
                dataItem.ActId = actId?.ToString();
            
            if (itemDict.TryGetValue("act_name", out var actName))
                dataItem.ActName = actName?.ToString();
            
            if (itemDict.TryGetValue("act_status", out var actStatus))
                dataItem.Status = actStatus?.ToString(); // 映射act_status到status
            
            if (itemDict.TryGetValue("start_time", out var startTime))
                dataItem.StartTime = startTime?.ToString();
            
            if (itemDict.TryGetValue("end_time", out var endTime))
                dataItem.EndTime = endTime?.ToString();
            
            // 处理可能存在的其他字段
            if (itemDict.TryGetValue("sponsor_id", out var sponsorId))
                dataItem.SponsorId = sponsorId?.ToString();
            
            if (itemDict.TryGetValue("sponsor_name", out var sponsorName))
                dataItem.SponsorName = sponsorName?.ToString();
            
            if (itemDict.TryGetValue("act_type", out var actType))
                dataItem.ActType = actType?.ToString();
            
            if (itemDict.TryGetValue("create_time", out var createTime))
                dataItem.CreateTime = createTime?.ToString();
            
            if (itemDict.TryGetValue("update_time", out var updateTime))
                dataItem.UpdateTime = updateTime?.ToString();
            
            return dataItem;
        }
    }
} 